package cn.itcast.manus.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itcast.manus.agent.Agent;
import cn.itcast.manus.agent.AgentFactory;
import cn.itcast.manus.dto.DialogMessageDTO;
import cn.itcast.manus.enums.AgentTypeEnum;
import cn.itcast.manus.message.WSSessionManagement;
import cn.itcast.manus.service.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WebSocketServiceImpl implements WebSocketService {

    private final WSSessionManagement wsSessionManagement;
    private final ExecutorService executor = Executors.newCachedThreadPool();

    @Override
    public void enhancedDialog(DialogMessageDTO message, SimpMessageHeaderAccessor headerAccessor) {
        if(StrUtil.isEmpty(message.getText())){
            log.info("receive empty message!!!");  //若为空
            return;
        }

        // 获取会话id
        var sessionId = headerAccessor.getSessionId();
        // 根据会话id获取对话对象
        var wsSession = this.wsSessionManagement.sessionDialog(sessionId);
        // 将消息对象写入到会话中
        wsSession.receiveMessages(message);
        // 通过智能体进行处理业务
        Agent agent = AgentFactory.getAgent(AgentTypeEnum.RE_ACT_PLANNING_AGENT).apply(wsSession);
        Runnable runnable = () -> {
            try {
                // 获取客户端发来的消息
                var task = wsSession.readMessage();
                // 通过规划agent进行执行
                var finalResult = agent.solveTask(task);
                log.info("complete with final result:{}", finalResult);
                //给客户端发消息
                wsSession.sendMessage(finalResult);
                wsSession.sendMessage("任务流程结束");
            }finally {
                wsSessionManagement.clean(sessionId);
            }
        };
        executor.execute(runnable);


       /* //对客户端发送消息   wsSession 实体包含消息发送对象 消息sessionId等信息
        wsSession.sendMessage("消息已收到！");*/
    }
}
